﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Domain.Entities;
using Domain.UnitOfWork;
using Mestedur.ViewModels;
using Services;

namespace Mestedur.Controllers
{
    public class MainPageController : Controller
    {
        //
        // GET: /Index/

        private IEditorService editorService;
        private IDatabaseService databaseService;
        private IUnitOfWorkFactory unitOfWorkFactory;

        public MainPageController(IEditorService editorService, IUnitOfWorkFactory unitOfWorkFactory, IDatabaseService databaseService)
        {
            this.editorService = editorService;
            this.unitOfWorkFactory = unitOfWorkFactory;
            this.databaseService = databaseService;
        }

        [Authorize]
        public ActionResult Index()
        {
            using (unitOfWorkFactory.Create())
            {
                var courses = databaseService.Courses.GetAll();
                var viewModel = ConvertCourseToCourseViewModel(courses);
                return View(viewModel);
            }
        }

        private IEnumerable<CourseViewModel> ConvertCourseToCourseViewModel(IEnumerable<Course> courses)
        {
            var result = new List<CourseViewModel>();

            foreach (var course in courses)
            {
                result.Add(new CourseViewModel() { Topics = ConvertTopicToTopicViewModel(course.Topics), CourseName = course.CourseName, Id = course.Id });
            }

            return result;
        }

        private IEnumerable<TopicViewModel> ConvertTopicToTopicViewModel(IEnumerable<Topic> topics)
        {
            var result = new List<TopicViewModel>();

            foreach (var topic in topics)
            {
                result.Add(new TopicViewModel() { Chapters = ConvertChaptersToChaptersViewModel(topic.Chapters), TopicName = topic.TopicName, Id = topic.Id });
            }
            return result;
        }

        private IEnumerable<ChapterViewModel> ConvertChaptersToChaptersViewModel(IEnumerable<Chapter> chapters)
        {
            var result = new List<ChapterViewModel>();

            foreach (var chapter in chapters)
            {
                result.Add(new ChapterViewModel() { ChapterData = chapter.ChapterData, ChapterName = chapter.ChapterName, Id = chapter.Id, TopicId = chapter.Topic.Id });
            }
            return result;
        }
    }
}
